package com.mijie.homi.api;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.mijie.core.ApplicationProperties;
import com.mijie.core.Status;
import com.mijie.homi.common.constant.CategoryCode;
import com.mijie.homi.common.constant.HomiConstants;
import com.mijie.homi.common.constant.HomiStatusCode;
import com.mijie.homi.common.domain.chat.ChatMessage;
import com.mijie.homi.common.domain.user.DeviceInfo;
import com.mijie.homi.common.domain.user.User;
import com.mijie.homi.common.domain.user.UserExtInfo;
import com.mijie.homi.common.util.HomiUtil;
import com.mijie.homi.service.chat.ChatService;
import com.mijie.homi.service.user.DeviceInfoService;
import com.mijie.homi.service.user.UserExtInfoService;
import com.mijie.homi.service.user.UserService;
import com.mijie.homi.util.ServerHelper;
import com.mijie.util.FileUploadUtil;
import com.mijie.util.Helper;
import com.mijie.util.IOUtil;
import com.mijie.util.ImageUtil;

@Controller
@RequestMapping("/chat")
public class ChatApi {
	
	@Autowired
	private ChatService chatService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserExtInfoService extInfoService;
	@Autowired
	private DeviceInfoService deviceInfoService;
	private Logger logger  = Logger.getLogger(ChatApi.class);
	
	@RequestMapping(value="/upload/image",method=RequestMethod.POST)
	public @ResponseBody void uploadImage(MultipartHttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		Status status = new Status(request,response);
		MultipartFile file  = request.getFile("image");
		if(file==null){
			status.setCode(HomiStatusCode.PARAM_ABSENT);
			status.write();
			return;
		}
		
		if(!FileUploadUtil.validate(file, HomiConstants.IMAGE_MAX_SIZE ,HomiConstants.IMAGE_SUFFIX)){
			status.setCode(HomiStatusCode.UPLOAD_FILE_ILLEGAL);
			status.write();
			return;
		}
		
		
		String imageSmallHome = ApplicationProperties.get("chatimg.small.home");
		String imageLargeHome = ApplicationProperties.get("chatimg.large.home");
		String basePath = ApplicationProperties.get("resource.path");
		String imageName = FileUploadUtil.uploadAndNoChangeName(file, basePath+imageLargeHome);
		if(imageName==null) status.setCode(HomiStatusCode.UPLOAD_FILE_FAIL);
		else{
			File src = new File(basePath+imageLargeHome+imageName);
			File dest = new File(basePath+imageSmallHome+imageName);
			ImageUtil.zoomWithFixWidth(src, dest, 190, 0.8f);
		}
		status.setResult("{\"image\":\""+imageName+"\",\"smallResPath\":\""+HomiUtil.getRealUrl(imageSmallHome)+"\",\"largeResPath\":\""+HomiUtil.getRealUrl(imageLargeHome)+"\"}");
		status.write();
	}
	
	@RequestMapping(value="/upload/voice",method=RequestMethod.POST)
	public @ResponseBody void uploadVoice(MultipartHttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		Status status = new Status(request,response);
		MultipartFile file  = request.getFile("voice");
		if(file==null){
			status.setCode(HomiStatusCode.PARAM_ABSENT);
			status.write();
			return;
		}
		
		if(!FileUploadUtil.validate(file,HomiConstants.VOICE_MAX_SIZE ,HomiConstants.VOICE_SUFFIX)){
			status.setCode(HomiStatusCode.UPLOAD_FILE_ILLEGAL);
			status.write();
			return;
		}
		
		String voiceHome = ApplicationProperties.get("chat.voice.home");
		String basePath = ApplicationProperties.get("resource.path");
		String voiceName = FileUploadUtil.uploadAndNoChangeName(file, basePath+voiceHome);
		if(voiceName==null){
			status.setCode(HomiStatusCode.UPLOAD_FILE_FAIL);
			voiceName = "";
		}
		status.setResult("{\"voice\":\""+voiceName+"\",\"resPath\":\""+HomiUtil.getRealUrl(voiceHome)+"\"}");
		status.write();
	}
	
	
	
	@RequestMapping(value="/message/list",method=RequestMethod.GET)
	public @ResponseBody void listMessage(HttpServletRequest request,HttpServletResponse response) throws IOException{
		Integer userId = ServerHelper.getUserId(request);
		Status status = new Status(request,response);
		List<ChatMessage> chatMessageList = chatService.listChatMessage(userId);
		JSONArray result = new JSONArray();
		JSONObject json = null;
		User user = null;
		UserExtInfo extInfo = null;
		DeviceInfo deviceInfo = null; 
		if(!chatMessageList.isEmpty()){
			ChatMessage cm = null;
			Iterator<ChatMessage> iter = chatMessageList.iterator();
			while(iter.hasNext()){
				cm = iter.next();
				iter.remove();
				user =  userService.getUserById(cm.getSender());
				extInfo = extInfoService.getUserExtInfoByUserId(cm.getSender());
				if(extInfo==null || user==null) continue;
				cm.setAvatar(user.getAvatar());
				cm.setGender(user.getGender());
				cm.setMood(extInfo.getMood());
				cm.setLastLoginAt(extInfo.getLastLoginAt());
				cm.setLatitude(extInfo.getLatitude());
				cm.setLongitude(extInfo.getLongitude());
				cm.setNickName(user.getNickName());
				
				json = JSONObject.fromObject(cm);
				boolean ignoreVoice = false;
				deviceInfo = deviceInfoService.getDeviceInfo(extInfo.getDeviceId());
				String clientAppVer = deviceInfo.getAppVer();
				if(extInfo.getOs().equalsIgnoreCase("android")){
					ignoreVoice = Helper.versionLessThan(clientAppVer, "1.0.2");
				}else{
					ignoreVoice = Helper.versionLessThan(clientAppVer, "1.0.3");
				}
				if(cm.getCategory()==CategoryCode.CHAT_VOICE){
					if(ignoreVoice){
						json.put("category", CategoryCode.CHAT_TEXT_MESSAGE);
						json.put("message", "系统提示:此版本无法支持语音，请更新软件");
					}else{
						json.put("message", cm.getMessage().trim().isEmpty()?"":ApplicationProperties.get("resource.url")+cm.getMessage());
					}
				}
				json.put("avatar", HomiUtil.getRealUrl(user.getAvatar()));
				json.put("lastLoginAt", extInfo.getLastLoginAt().getTime());
				json.put("smallImage", HomiUtil.getRealUrl(cm.getSmallImage()));
				json.put("largeImage", HomiUtil.getRealUrl(cm.getLargeImage()));
				json.put("createAt", cm.getCreateAt().getTime());
				result.add(json.toString());
			}
			iter = null;
			chatMessageList = null;
		}
		status.setResult(result);
		status.write();
	}
	
	
	@RequestMapping(value="/block_user",method=RequestMethod.POST)
	public @ResponseBody void blockUser(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String content = IOUtil.getContent4InputStream(request.getInputStream());
		JSONObject json = JSONObject.fromObject(content);
		Status status = new Status(request,response);
		chatService.blockUser(ServerHelper.getUserId(request), json.getInt("targetId"));
		status.write();
	}
	
	@RequestMapping(value="/unblock_user",method=RequestMethod.POST)
	public @ResponseBody void unblockUser(HttpServletRequest request,HttpServletResponse response) throws IOException{
		Status status = new Status(request,response);
		String content = IOUtil.getContent4InputStream(request.getInputStream());
		JSONObject json = JSONObject.fromObject(content);
		chatService.unblockUser(ServerHelper.getUserId(request), json.getInt("targetId"));
		status.write();
	}
}
